#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, const char *argv[])
{
	int sockfd=socket(AF_INET,SOCK_STREAM,0);

	struct sockaddr_in serveraddr,clientaddr;
	serveraddr.sin_addr.s_addr=inet_addr(argv[1]);
	serveraddr.sin_family=AF_INET;
	serveraddr.sin_port=htons(atoi(argv[2]));

	socklen_t addrlen=sizeof(serveraddr);
	bind(sockfd,(struct sockaddr *)&serveraddr,addrlen);
	
	listen(sockfd,5);

	char buf[128]={0};

	fd_set myreadfds; 
	FD_ZERO(&myreadfds);

	while(1)
	{
		FD_SET(0,&myreadfds);	
		FD_SET(sockfd,&myreadfds);

		select(sockfd+1,&myreadfds,NULL,NULL,NULL);

		if((FD_ISSET(0,&myreadfds))==1)
		{
			fgets(buf,128,stdin);
			printf("buf:%s\n",buf);
			memset(buf,0,128);
		}

		if((FD_ISSET(sockfd,&myreadfds))==1)
		{
			int acceptfd=accept(sockfd,(struct sockaddr *)&serveraddr,&addrlen);
			printf("%s has connect\n",inet_ntoa(serveraddr.sin_addr));
		}
	}
	
	return 0;
}
